package com.itita.ww2.game.worldmap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itita.ww2.core.WW2Exception;
import com.itita.ww2.data.WorldMapConfig;
import com.itita.ww2.data.WorldMapConfig.PermType;
import com.itita.ww2.enums.WW2ExceptionCode;
import com.itita.ww2.game.alliance.AllianceManager;
import com.itita.ww2.game.user.UserService;
import com.itita.ww2.game.user.event.UserEventDispatch;
import com.itita.ww2.game.worldmap.event.WorldMapEventDispatch;
import com.itita.ww2.handler.requesthandler.worldmap.utils.BattleLogUtil;
import com.itita.ww2.handler.requesthandler.worldmap.utils.WorldMapUtils;
import com.itita.ww2.model.user.UserProfile;
import com.itita.ww2.model.user.battle.BaseBattleState.BattleType;
import com.itita.ww2.model.user.battle.WorldBattleState;
import com.itita.ww2.model.worldmap.Base;
import com.itita.ww2.model.worldmap.Block;
import com.itita.ww2.model.worldmap.City;
import com.itita.ww2.model.worldmap.UserUnlockDataMgr;
import com.itita.ww2.model.worldmap.enums.BaseActionEnum;
import com.itita.ww2.model.worldmap.enums.CityActionEnum;
import com.itita.ww2.model.worldmap.enums.CityType;
import com.itita.ww2.model.worldmap.enums.StatusEnum;
import com.itita.ww2.puredb.model.Alliance;
import com.itita.ww2.puredb.model.AllianceMember;
import com.itita.ww2.utils.TimeUtil;
import com.smartfoxserver.v2.entities.data.ISFSArray;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSArray;
import com.smartfoxserver.v2.entities.data.SFSObject;

/**
 * 世界地图服务(管理器)
 * @author NorthLan
 *
 */
public class WorldMapService {
	private static final Logger logger = LoggerFactory.getLogger(WorldMapService.class);

	/**
	 * 获取大地图数据
	 */
	public static ISFSArray getWorldMapData(UserProfile userProfile) {
		Map<Integer, List<Integer>> userUnlockData = userProfile.getWMManager().getUserUnlockDataMgr().getUnlockData();
		// 所有区块遍历
		ISFSArray ret = SFSArray.newInstance();
		for (Block block : WorldMapManager.getInstance().getAllBlock()) {
			ISFSObject blockObj = SFSObject.newInstance();
			// 区块的解锁状态
			boolean blockUnlocked = UserUnlockDataMgr.isBlockUnlocked(userUnlockData, block.getId());
			blockObj.putInt("blockId", block.getId());
			blockObj.putBool("unlocked", blockUnlocked);
			// citylist
			ISFSArray cityList = SFSArray.newInstance();
			for (City city : block.getAllCity()) {
				cityList.addSFSObject(getCityData(userProfile, userUnlockData, city));
			}
			blockObj.putSFSArray("list", cityList);
			ret.addSFSObject(blockObj);
		}
		return ret;
	}

	/**
	 * 获取城池数据
	 */
	public static ISFSObject getCityData(UserProfile userProfile, Map<Integer, List<Integer>> userUnlockData,
			City city) {
		if (userUnlockData == null) {
			userUnlockData = userProfile.getWMManager().getUserUnlockDataMgr().getUnlockData();
		}
		ISFSObject ret = SFSObject.newInstance();
		String ownerAid = city.getOwnerAid();
		String declarAid = city.getDeclarAid();
		CityType cityType = city.getType();
		DateTime lastOccTime = city.getLastOccTime();
		//
		ret.putUtfString("mission", WorldMapConfig.getCityMissionId(city.getParentBlock().getId(), city.getId())); // mission
		ret.putInt("cityId", city.getId()); // cityId
		ret.putInt("blockId", city.getBlockId());
		// ownerAid
		boolean hasOwnerAid = ownerAid != null && StringUtils.isNotBlank(ownerAid);
		if (hasOwnerAid) {
			Alliance alliance = AllianceManager.getInstance().getAlliance(ownerAid);
			if (alliance == null) {
				logger.warn("Alliance [{}] not found!", ownerAid);
			}
			ret.putUtfString("ownerAid", ownerAid);
			ret.putUtfString("ownerCountry", alliance != null ? alliance.getCountry() : "XX");
			ret.putUtfString("ownerAName", alliance != null ? alliance.getName() : "Unknown");
		}
		// declarAid
		boolean hasDiclarAid = declarAid != null && StringUtils.isNotBlank(declarAid);
		if (hasDiclarAid) {
			Alliance alliance = AllianceManager.getInstance().getAlliance(declarAid);
			if (alliance == null) {
				logger.warn("Alliance [{}] not found!", ownerAid);
			}
			ret.putUtfString("declarAid", ownerAid);
			ret.putUtfString("declarCountry", alliance != null ? alliance.getCountry() : "XX");
			ret.putUtfString("declarAName", alliance != null ? alliance.getName() : "Unknown");
		}
		// CD
		boolean isCityBattleCD = TimeUtil.isCooldown(lastOccTime, WorldMapConfig.getCityBattleCD(cityType.getValue()));
		if (isCityBattleCD) {
			ret.putLong("endTime",
					lastOccTime.plusSeconds(WorldMapConfig.getCityBattleCD(cityType.getValue())).getMillis());
		}
		CityActionEnum action = CityActionEnum.UNKNOWN;
		boolean isBlockUnlocked = UserUnlockDataMgr.isBlockUnlocked(userUnlockData, city.getBlockId());
		boolean isCityUnlocked = UserUnlockDataMgr.isCityUnlocked(userUnlockData, city.getBlockId(), city.getId());
		if (isBlockUnlocked) {
			if (isCityUnlocked) {
				if (userProfile.isJoinAlliance()) {
					if (isCityBattleCD) {
						if (hasOwnerAid && ownerAid.equals(userProfile.getAid())) {
							// 被己方占领
							action = CityActionEnum.OPEN;
						} else {
							// 冷却中
							action = CityActionEnum.COOLDOWN;
						}
					} else {
						if (cityType == CityType.DEFAULT) {
							action = CityActionEnum.OPEN; // 普通城池
						} else if (cityType == CityType.CAPTICAL) {
							// 都城
							if (hasOwnerAid) {
								if (ownerAid.equals(userProfile.getAid())) {
									// 被己方占领
									action = CityActionEnum.OPEN;
								} else {
									// 其他联盟占领
									if (WorldMapUtils.cityWarTimePeriod()) {
										// 处于城战时间
										if (hasDiclarAid) {
											if (userProfile.getAid().equals(declarAid)) {
												action = CityActionEnum.OPEN; // 本盟宣战
											} else {
												action = CityActionEnum.DECLARED; // 被其他盟宣战
											}
										} else {
											action = CityActionEnum.NEED_DECLAR; // 需要宣战
										}
									} else {
										action = CityActionEnum.NOT_BATTLE_TIME;
									}
								}
							} else {
								// NPC占领
								if (WorldMapUtils.cityWarTimePeriod()) {
									action = CityActionEnum.OPEN;
								} else {
									action = CityActionEnum.NOT_BATTLE_TIME;
								}
							}
						}
					}
				} else {
					// 未加入联盟,不能进入
					action = CityActionEnum.USER_NOT_JOIN_ALLIANCE;
				}
			} else {
				int requireUnlockCity = WorldMapConfig.getCityRequireUnlockCity(city.getParentBlock().getId(),
						city.getId());
				int requireCMDLevel = WorldMapConfig.getCityRequireCMDLevel(city.getParentBlock().getId(),
						city.getId());
				if (userProfile.getUserInfo().getLevel() < requireCMDLevel) {
					action = CityActionEnum.LOCKED; // 指挥官等级未达到要求,直接locked
				} else {
					if (requireUnlockCity == -1
							|| userUnlockData.get(city.getParentBlock().getId()).contains(requireUnlockCity)) {
						// 需求为-1(没有前置) 或  需求的城池已解锁
						action = CityActionEnum.NEED_UNLOCK;
					} else {
						action = CityActionEnum.LOCKED;
					}
				}
			}
			ret.putBool("unlocked", isCityUnlocked);
		} else {
			action = CityActionEnum.LOCKED;
		}
		ret.putInt("action", action.getValue());
		ret.putInt("status", city.getStatus().getValue());
		return ret;
	}

	/**
	 * 获取城池据点列表
	 */
	public static ISFSArray getCityBaseList(int blockId, int cityId) {
		City city = WorldMapManager.getInstance().getCity(blockId, cityId);
		if (city == null) {
			logger.error("city: {}:{} not found!", blockId, cityId);
			return SFSArray.newInstance();
		}
		// 
		ISFSArray ret = SFSArray.newInstance();
		for (Base base : city.getAllBase()) {
			ret.addSFSObject(getBaseSimpleData(base));
		}
		return ret;
	}

	/**
	 * 获取据点简单信息
	 */
	public static ISFSObject getBaseSimpleData(Base base) {
		ISFSObject ret = SFSObject.newInstance();
		ret.putInt("baseId", base.getId());
		int ownerUid = base.getOwnerUid();
		int underAtkId = base.getUnderAtkUid();
		// 
		ret.putInt("ownerUid", ownerUid);
		ret.putInt("underAtkId", underAtkId);
		ret.putInt("status", base.getStatus().getValue());
		if (ownerUid != -1) {
			// 用户名和国家  uName,uCountry
			UserProfile ownerProfile = UserService.getInstance().getUserProfile(ownerUid);
			ret.putUtfString("ownerName", ownerProfile.getNickname());
			ret.putUtfString("ownerCountry", ownerProfile.getCountry());
			ret.putUtfString("ownerAid", ownerProfile.getAid());
		}
		if (underAtkId != -1) {
			// 用户名和国家
			UserProfile underAtkProfile = UserService.getInstance().getUserProfile(underAtkId);
			ret.putUtfString("underAtkName", underAtkProfile.getNickname());
			ret.putUtfString("underAtkCountry", underAtkProfile.getCountry());
		}
		// 据点冷却时间
		DateTime lastOccTime = base.getLastOccTime();
		if (TimeUtil.isCooldown(lastOccTime, WorldMapConfig.getBaseBattleCD())) {
			ret.putLong("endTime", lastOccTime.plusSeconds(WorldMapConfig.getBaseBattleCD()).getMillis());
		}
		return ret;
	}

	/**
	 * 获取据点数据(针对玩家个体)
	 */
	public static ISFSObject getBaseData(UserProfile userProfile, int blockId, int cityId, int baseId) {
		ISFSObject ret = SFSObject.newInstance();
		// 获取据点数据
		Base base = WorldMapManager.getInstance().getBase(blockId, cityId, baseId);
		if (base == null) {
			logger.error("base {}:{}:{} not found!", blockId, cityId, baseId);
			return ret;
		}
		int ownerUid = base.getOwnerUid();
		// 
		StatusEnum status = base.getStatus();
		BaseActionEnum action = BaseActionEnum.UNKNOWN; // 默认状态 - 未知
		if (status == StatusEnum.UNDER_ATTACK) {
			action = BaseActionEnum.CLOSE;
		} else {
			if (ownerUid != -1) {
				// 据点被占领
				UserProfile ownerProfile = UserService.getInstance().getUserProfile(ownerUid);
				ret.putUtfString("ownerName", ownerProfile.getNickname());

				Alliance alliance = AllianceManager.getInstance().getAlliance(ownerProfile.getAid());
				if (alliance == null) {
					logger.warn("Alliance id:{} not found!", ownerProfile.getAid());
				} else {
					ret.putUtfString("aName", alliance.getName());
				}
				// 自己和己方联盟 
				if (ownerProfile.getUid() == userProfile.getUid() || ownerProfile.getAid() == userProfile.getAid()) {
					action = BaseActionEnum.CLOSE;
				} else {
					// 第三方占领
					action = BaseActionEnum.OPEN;
				}
			} else {
				action = BaseActionEnum.OPEN;
			}
		}

		// 据点冷却时间
		DateTime lastOccTime = base.getLastOccTime();
		if (TimeUtil.isCooldown(lastOccTime, WorldMapConfig.getBaseBattleCD())) {
			action = BaseActionEnum.BASE_COOLDOWN;
			ret.putLong("endTime", lastOccTime.plusSeconds(WorldMapConfig.getBaseBattleCD()).getMillis());
		}

		// 作战时间 & 冷却时间 (解决玩家呆在城内不出,城战结束跳过冷却的问题)
		CityType cityType = base.getParentCity().getType();
		ret.putInt("type", cityType.getValue());
		if (cityType == CityType.CAPTICAL) {
			// 都城非作战时间是不能打的
			if (!WorldMapUtils.cityWarTimePeriod()) {
				action = BaseActionEnum.NOT_BATTLE_TIME;
			}
		}

		// 城池冷却时间
		if (TimeUtil.isCooldown(base.getParentCity().getLastOccTime(),
				WorldMapConfig.getCityBattleCD(cityType.getValue()))) {
			action = BaseActionEnum.CITY_COOLDOWN;
		}
		// 
		ret.putInt("lv", base.getLevel());
		ret.putInt("action", action.getValue());
		ret.putInt("status", status.getValue());
		ret.putInt("ownerUid", ownerUid);
		return ret;
	}

	/**
	 * 获取最新战报(天下大势)
	 */
	public static ISFSArray getLastestBattle() {
		List<Map<String, String>> lastestList = WorldMapManager.getInstance().getCacheLastestBattleTable().sort("time",
				1, -1, true);
		ISFSArray arr = new SFSArray();
		for (Map<String, String> val : lastestList) {
			ISFSObject obj = new SFSObject();
			int type = Integer.valueOf(val.get("type"));
			obj.putInt("type", type);
			obj.putUtfString("uName", val.get("uName"));
			obj.putInt("cityId", Integer.valueOf(val.get("cityId")));
			obj.putInt("blockId", Integer.valueOf(val.get("blockId")));
			switch (type) {
			case 0:
				obj.putUtfString("aNameA", val.get("aNameA"));
				obj.putUtfString("aNameB", val.get("aNameB"));
				break;
			case 1:
			case 4:
				obj.putUtfString("aName", val.get("aName"));
				break;
			case 2:
			case 3:
				obj.putInt("baseId", Integer.valueOf(val.get("baseId")));
				break;
			}
			arr.addSFSObject(obj);
		}
		return arr;
	}

	/**
	 * 添加战报(天下大势)
	 */
	public static void addBattleLog(Map<String, String> hash) {
		WorldMapManager.getInstance().getCacheLastestBattleTable().addValue(hash);
	}

	/**
	 * 据点升级捐献
	 */
	public static boolean baseUpgradeDonate(UserProfile userProfile, ISFSObject resObj, int blockId, int cityId,
			int baseId) {
		if (!userProfile.getResManager().isResEnoughMulti(resObj)) {
			return false;
		}
		// 据点资源池投入
		Base base = WorldMapManager.getInstance().getBase(blockId, cityId, baseId);
		boolean flag = base.upgradeDonate(resObj);
		UserEventDispatch.onBaseLvDonate(userProfile, base, resObj, flag);
		// 扣除资源
		userProfile.getResManager().operResWithMaxCheck(resObj, false);
		userProfile.getResManager().update();
		userProfile.getResManager().sync();
		return true;
	}

	/**
	 * 据点强化捐献
	 */
	public static boolean baseEnhanceDonate(UserProfile userProfile, ISFSObject resObj, int blockId, int cityId,
			int baseId) {
		if (!userProfile.getResManager().isResEnoughMulti(resObj)) {
			return false;
		}
		// 据点资源池投入
		Base base = WorldMapManager.getInstance().getBase(blockId, cityId, baseId);
		boolean flag = base.enhanceDonate(resObj);
		UserEventDispatch.onBaseEnDonate(userProfile, base, resObj, flag);
		// 扣除资源
		userProfile.getResManager().operResWithMaxCheck(resObj, false);
		userProfile.getResManager().update();
		userProfile.getResManager().sync();
		return true;
	}

	/**
	 * 玩家攻击据点
	 */
	public static void attackBase(UserProfile userProfile, ISFSObject army, int blockId, int cityId, int baseId)
			throws WW2Exception {
		Base base = WorldMapManager.getInstance().getBase(blockId, cityId, baseId);
		// 被攻击状态不能打
		if (base.getStatus() == StatusEnum.UNDER_ATTACK) {
			throw new WW2Exception(WW2ExceptionCode.WORLDMAP_BASE_UNDER_ATTACK);
		}
		// 据点冷却时间
		DateTime lastOccTime = base.getLastOccTime();
		if (TimeUtil.isCooldown(lastOccTime, WorldMapConfig.getBaseBattleCD())) {
			throw new WW2Exception(WW2ExceptionCode.WORLDMAP_BASE_COOLDOWN);
		}

		// 作战时间 & 冷却时间 (解决玩家呆在城内不出,城战结束跳过冷却的问题)
		CityType cityType = base.getParentCity().getType();
		if (cityType == CityType.CAPTICAL) {
			// 都城非作战时间是不能打的
			if (!WorldMapUtils.cityWarTimePeriod()) {
				throw new WW2Exception(WW2ExceptionCode.WORLDMAP_CITY_NOT_BATTLE_TIME);
			}
		}
		// 城池冷却时间
		if (TimeUtil.isCooldown(base.getParentCity().getLastOccTime(),
				WorldMapConfig.getCityBattleCD(cityType.getValue()))) {
			throw new WW2Exception(WW2ExceptionCode.WORLDMAP_CITY_COOLDOWN);
		}

		userProfile.getBattleManager().enterBattle(BattleType.WorldBattle, army, base);

		// 设定据点状态
		base.underAttack(userProfile.getUid());

		// 触发事件
		WorldMapEventDispatch.onBaseDataUpdate(base);
	}

	/**
	 * 攻击据点结束<br>
	 * 攻击据点的玩家必然已经加入了联盟
	 */
	public static void attackBaseEnd(UserProfile userProfile, ISFSObject army, boolean victory) throws WW2Exception {
		WorldBattleState userState = userProfile.getBattleManager().getBattleState(BattleType.WorldBattle);
		if (userState == null) {
			throw new WW2Exception();
		}
		userState.setLastBattleArmy(army);
		userProfile.getBattleManager().endBattle(true, victory);
		// 
		Base base = userState.getBase();
		City city = base.getParentCity();
		int preOwnerUid = base.getOwnerUid();

		if (victory) {
			CityType cityType = city.getType();
			// 城池冷却时间
			if (TimeUtil.isCooldown(city.getLastOccTime(), WorldMapConfig.getCityBattleCD(cityType.getValue()))) {
				throw new WW2Exception(WW2ExceptionCode.WORLDMAP_CITY_COOLDOWN);
			}

			// 非城战时间,不能占领(再次判断,避免时间问题)
			if (cityType == CityType.CAPTICAL && !WorldMapUtils.cityWarTimePeriod()) {
				base.resetUnderAtk();
				WorldMapEventDispatch.onBaseDataUpdate(base);
				throw new WW2Exception(WW2ExceptionCode.WORLDMAP_CITY_NOT_BATTLE_TIME);
			}
			// 未加入联盟(中途被Kick)
			if (!userProfile.isJoinAlliance()) {
				base.resetUnderAtk();
				WorldMapEventDispatch.onBaseDataUpdate(base);
				throw new WW2Exception(WW2ExceptionCode.ALLIANCE_HAS_NOT_JOIN);
			}

			// 之前的城池状态
			StatusEnum preCityStatus = base.getParentCity().getStatus();
			String preCityOwnerAid = base.getParentCity().getOwnerAid();

			base.occupied(userProfile.getUid()); // 占领据点
			WorldMapEventDispatch.onBaseDataUpdate(base);
			// 刷新城池状态
			boolean cityOwnerChanged = city.refreshOwnerState();
			city.refreshStatus();

			UserEventDispatch.onUserOccupiedBase(userProfile, UserService.getInstance().getUserProfile(preOwnerUid),
					preCityOwnerAid, base);

			// 战报 log2
			addBattleLog(
					BattleLogUtil.log2(userProfile.getNickname(), base.getBlockId(), base.getCityId(), base.getId()));

			// 现在的城池状态
			StatusEnum nowCityStatus = base.getParentCity().getStatus();
			// String nowCityOwnerAid = base.getParentCity().getOwnerAid();

			if (preCityStatus == nowCityStatus) {
				return;
			}
			WorldMapEventDispatch.onCityDataUpdate(base.getParentCity());

			if (nowCityStatus == StatusEnum.UNDER_ATTACK) {
				// 被攻击了
				WorldMapEventDispatch.onCityUnderAttack(city, userProfile);
			} else if (cityOwnerChanged && nowCityStatus == StatusEnum.DEFAULT) {
				if (StringUtils.isBlank(preCityOwnerAid)) {
					// 占领NPC城池 战报
					Alliance alliance = AllianceManager.getInstance().getAlliance(userProfile.getAid());
					String aName = "";
					if (alliance != null) {
						aName = alliance.getName();
					}
					addBattleLog(BattleLogUtil.log1(userProfile.getNickname(), aName, city.getBlockId(), city.getId()));
				} else {
					// 被抢夺  战报
					Alliance alliance = AllianceManager.getInstance().getAlliance(userProfile.getAid());
					String aName = "";
					if (alliance != null) {
						aName = alliance.getName();
					}
					Alliance preAlliance = AllianceManager.getInstance().getAlliance(userProfile.getAid());
					String preAName = "";
					if (preAlliance != null) {
						preAName = preAlliance.getName();
					}
					addBattleLog(BattleLogUtil.log0(userProfile.getNickname(), aName, preAName, city.getBlockId(),
							city.getId()));
				}
				// 被占领
				WorldMapEventDispatch.onCityOccupied(city, userProfile, preCityOwnerAid);
			}
		} else {
			// 添加失败战报 log3
			UserProfile preOwnerProfile = UserService.getInstance().getUserProfile(preOwnerUid);
			if (preOwnerProfile != null) {
				addBattleLog(BattleLogUtil.log3(preOwnerProfile.getNickname(), base.getBlockId(), base.getCityId(),
						base.getId()));
			}
			// 还原据点状态
			base.resetUnderAtk();
			WorldMapEventDispatch.onBaseDataUpdate(base);

			UserEventDispatch.onUserDefeatedBase(userProfile, preOwnerProfile, base);
		}
	}

	/**
	 * 检查权限
	 */
	private static AllianceMember checkPerm(AllianceMember am, PermType permType) throws WW2Exception {
		if (am == null) {
			throw new WW2Exception();
		}
		if (!WorldMapConfig.hasPermission(permType, am.getRole())) {
			throw new WW2Exception(WW2ExceptionCode.USER_NO_PERMISSION);
		}
		return am;
	}

	/**
	 * 宣战
	 */
	public static void declarWar(UserProfile userProfile, int blockId, int cityId) throws WW2Exception {
		if (!userProfile.isJoinAlliance()) {
			throw new WW2Exception(WW2ExceptionCode.ALLIANCE_HAS_NOT_JOIN);
		}
		City city = WorldMapManager.getInstance().getCity(blockId, cityId);

		city.checkDeclarable(userProfile.getAid());

		Alliance alliance = AllianceManager.getInstance().getAlliance(userProfile.getAid());
		// 联盟解散时不能宣战
		if (alliance.isDisband()) {
			throw new WW2Exception(WW2ExceptionCode.ALLIANCE_DISBANDING_STATUS);
		}
		// 权限判定
		AllianceMember am = checkPerm(AllianceMember.getByUid(userProfile.getUid()), PermType.DECLAR);

		// 时间限定
		if (!WorldMapUtils.cityWarTimePeriod()) {
			throw new WW2Exception(WW2ExceptionCode.WORLDMAP_CITY_NOT_BATTLE_TIME);
		}

		// // 宣战次数限定
		//		int nowTimes = WorldMapService.getInstance().getAllianceDeclarTimes(aid);
		//		if (nowTimes >= cityServerCfg.getInt("declarNumber")) {
		//			MessageHandler.getInstance().sendMsg(requestCMD, null, user, MsgCode.WORLDMAP_ALLIANCE_NO_DECLAR_TIMES,
		//					false);
		//			return false;
		//		}

		// 宣战
		city.setDeclarAid(userProfile.getAid());
		city.setLastDeclarTime(TimeUtil.getUtcNow());

		// 事件
		WorldMapEventDispatch.onCityDataUpdate(city);
		WorldMapEventDispatch.onCityDeclared(city, userProfile, alliance, am, city.getOwnerAid());
	}

	//////////////////////////// Reset ////////////////////////////////
	public static void resetWorldMapStateByUid(int uid) {
		List<City> changedCity = new ArrayList<>();
		for (City city : WorldMapManager.getInstance().getAllCity()) {
			int changedBase = 0;
			for (Base base : city.getAllBase()) {
				if (base.getOwnerUid() == uid) {
					base.reset();
					++changedBase;
				}
			}
			if (changedBase > 0) {
				city.refreshOwnerState();
				city.refreshStatus();
				changedCity.add(city);
				// 
				WorldMapEventDispatch.onAllBaseDataUpdate(city);
			}
		}
		int changeCitySize = changedCity.size();
		if (changeCitySize > 1) {
			WorldMapEventDispatch.onAllCityDataUpdate();
		} else if (changeCitySize == 1) {
			WorldMapEventDispatch.onCityDataUpdate(changedCity.get(0));
		}
	}

	public static void resetWorldMapCityState(String aid) {
		for (City city : WorldMapManager.getInstance().getAllCity()) {
			if (city.getOwnerAid().equals(aid)) {
				city.setOwnerAid("");
			}
			if (city.getDeclarAid().equals(aid)) {
				city.setDeclarAid("");
				city.setLastDeclarTime(null);
			}
		}
	}

	public static void resetWorldMapStateByUids(List<Integer> uids) {
		for (City city : WorldMapManager.getInstance().getAllCity()) {
			boolean isBaseChanged = false;
			for (Base base : city.getAllBase()) {
				if (uids.contains(base.getOwnerUid())) {
					base.reset();
					isBaseChanged = true;
				}
			}
			if (isBaseChanged) {
				city.refreshOwnerState();
				city.refreshStatus();

				WorldMapEventDispatch.onAllBaseDataUpdate(city);
			}
		}
		WorldMapEventDispatch.onAllCityDataUpdate();
	}

	/**
	 * 重置整个地图的数据(包含Base)
	 */
	public void resetWorldMapState() {
		for (City city : WorldMapManager.getInstance().getAllCity()) {
			for (Base base : city.getAllBase()) {
				base.reset();
			}
			city.reset();
		}
		//		// 所有玩家拥有据点数清零
		//		Table tabWMUserData = UserService.getInstance().getCacheWMUserDataTable();
		//		tabWMUserData.foreach((Map<String, String> item) -> {
		//			tabWMUserData.setValue(RedisUtil.genericKey(item.get("uid")), "base_count", 0);
		//		});
		//		// 所有联盟拥有  城池数量/据点数量  清零
		//		Table tabWMAllData = getAllianceDataTable();
		//		tabWMAllData.foreach((Map<String, String> item) -> {
		//			tabWMAllData.setValue(RedisUtil.genericKey(item.get("aid")), "base_count", 0);
		//			tabWMAllData.setValue(RedisUtil.genericKey(item.get("aid")), "city_count", 0);
		//		});
		//		// 
		//		pushAllCityUpdateMsg();
		//		pushAllBaseUpdateMsg();
	}
}
